//
//  RJUserData.m
//  AirQuality
//
//  Created by Po on 15/3/10.
//  Copyright (c) 2015年 Po. All rights reserved.
//

#import "RJUserData.h"

static RJUserData * userData = nil;

@interface RJUserData ()

@property (retain, nonatomic) NSArray * citys;
@property (retain, nonatomic) NSArray * cityCodes;
@property (retain, nonatomic) NSArray * cityNames;

- (void)initData;

@end

@implementation RJUserData

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initData];
    }
    return self;
}

+ (instancetype)defaultRJUserData
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        userData = [[self alloc] init];
    });
    return userData;
}
#pragma mark - user-defined initialization function
- (void)initData
{
    _isLogined = NO;
    _isRequestMessage = NO;
}

#pragma mark - function
- (void)setLoginState:(BOOL)isLogin
{
    _isLogined = isLogin;
}

- (void)updateMessageData
{
//    dispatch_queue_t mQueue = dispatch_queue_create("my.concurrent.queue", DISPATCH_QUEUE_CONCURRENT);
//    dispatch_async(mQueue, ^{
//        [self getMessageData];
//        [RJNetWork myNetRequestWithAddress:[[NetURL defaultURL] MessageStatus] data:@{@"timepoint":_messageTime} completeBlock:^(id responseObject) {
//            if (responseObject[@"result"] && [responseObject[@"data"] count] > 0) {
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"setMessageDataStatus" object:nil userInfo:@{@"haveData":@YES}];
//            }
//        } failBlack:^(id response) {
//            
//        }];
//    });
}

- (void)getMessageData
{
    static dispatch_once_t onceTokenData;
    dispatch_once(&onceTokenData, ^{
        NSDictionary * dic = [NSDictionary dictionaryWithContentsOfFile:GetFilePath(@"MessageData.plist")];
        _messageTime = dic[@"time"];
        if ([_messageTime isEqualToString:@""]) {
            _messageTime = [NSString stringWithFormat:@"%@ 00:00:00", [RJTools getTimeWithFormat:@"yyyy-MM-dd"]];
        }
    });
}

- (void)setMessageNotifaction:(BOOL)isOn complect:(void(^)(BOOL result))complectBlock
{
    if (isOn) {
        [self addLocalNotificationWithBlock:complectBlock];
    } else {
        [self removeNotifactionWithcategory:@"MessageLocalNotifaction" complect:complectBlock];
    }
}

-(void)addLocalNotificationWithBlock:(void(^)(BOOL result))complectBlock {
    dispatch_queue_t concurrentQueue = dispatch_queue_create("my.CreateNotifaction.queue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(concurrentQueue, ^{
        //通知按钮
        UIMutableUserNotificationAction *action1;
        action1 = [[UIMutableUserNotificationAction alloc] init];
        [action1 setActivationMode:UIUserNotificationActivationModeBackground];
        [action1 setTitle:@"Action 1"];
        [action1 setIdentifier:@"haha"];
        [action1 setDestructive:NO];
        [action1 setAuthenticationRequired:NO];
        
        UIMutableUserNotificationAction *action2;
        action2 = [[UIMutableUserNotificationAction alloc] init];
        [action2 setActivationMode:UIUserNotificationActivationModeBackground];
        [action2 setTitle:@"Action 2"];
        [action2 setIdentifier:@"hehe"];
        [action2 setDestructive:NO];
        [action2 setAuthenticationRequired:NO];
        
        UIMutableUserNotificationCategory *actionCategory;
        actionCategory = [[UIMutableUserNotificationCategory alloc] init];
        [actionCategory setIdentifier:@"ee"];
        [actionCategory setActions:@[action1, action2]
                        forContext:UIUserNotificationActionContextDefault];
        
        NSSet *categories = [NSSet setWithObject:actionCategory];
        UIUserNotificationType types = (UIUserNotificationTypeAlert|
                                        UIUserNotificationTypeSound|
                                        UIUserNotificationTypeBadge);
        
        UIUserNotificationSettings *settings;
        settings = [UIUserNotificationSettings settingsForTypes:types
                                                     categories:categories];
        
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        //定义本地通知对象
        UILocalNotification *notification=[[UILocalNotification alloc]init];
        NSDate *now=[NSDate date];
        //获得系统日期
        NSCalendar  * cal=[NSCalendar  currentCalendar];
        NSUInteger  unitFlags=NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit;
        NSDateComponents * conponent= [cal components:unitFlags fromDate:now];
        NSInteger year=[conponent year];
        NSInteger month=[conponent month];
        NSInteger day=[conponent day];
        //NSString *  nsDateString= [NSString  stringWithFormat:@"%4d年%2d月%2d日",year,month,day];
        //获得当天的9:00  时间
        NSString  * nsStringDate12 =  [NSString  stringWithFormat:@"%ld-%ld-%ld-%d-%d-%d",(long)year, (long)month,(long)day, 17,49,0  ];
        //根据时间字符串获得NSDate
        NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"YYYY-MM-dd-HH-mm-ss"];
        NSDate  * todayTwelve=[dateformatter dateFromString:nsStringDate12];
        
        //然后比较  now跟  todayTwelve那个大，如果已经过了12点，那就设置明天12点
        NSComparisonResult   dateResult =  [now  compare:todayTwelve ];
        if (dateResult ==  NSOrderedDescending  )
        {
            NSDate  *  tomorrowTwelve =  [todayTwelve  dateByAddingTimeInterval: 24 * 60 * 60];
            notification.fireDate =  tomorrowTwelve;
        }
        else
        {
            notification.fireDate= todayTwelve;
        }
//        notification.fireDate=[NSDate dateWithTimeIntervalSinceNow:10.0];//通知触发的时间，10s以后
//        notification.fireDate = [NSDate dateWithTimeIntervalSince1970:5*60*60*24];//本次开启立即执行的周期
//        notification.fireDate = currentDate;
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        
        [formatter setDateFormat:@"HH-mm"];
        
        NSDate *date = [formatter dateFromString:@"09-00"];
        notification.repeatInterval = kCFCalendarUnitDay;//通知重复次数
        notification.fireDate = date;
        //notification.repeatCalendar=[NSCalendar currentCalendar];//当前日历，使用前最好设置时区等信息以便能够自动同步时间
        notification.timeZone = [NSTimeZone defaultTimeZone];
        //设置通知属性
        notification.alertBody=@"今日数据审核提醒:请准时按要求审核数据"; //通知主体
//        notification.applicationIconBadgeNumber=1;//应用程序图标右上角显示的消息数
        notification.applicationIconBadgeNumber = [[[UIApplication sharedApplication] scheduledLocalNotifications]count] +1;
        notification.alertAction=@"打开应用"; //待机界面的滑动动作提示
        notification.alertLaunchImage=@"Default";//通过点击通知打开应用时的启动图片,这里使用程序启动图片
        //notification.soundName=UILocalNotificationDefaultSoundName;//收到通知时播放的声音，默认消息声音
        notification.soundName=@"msg.caf";//通知声音（需要真机才能听到声音）
        notification.category = @"MessageLocalNotifaction";
        
        //设置用户信息
        notification.userInfo=@{@"id":@1,@"user":@"Kenshin Cui"};//绑定到通知上的其他附加信息
        //调用通知
        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
        complectBlock(YES);
    });
}

- (void)removeNotifactionWithcategory:(NSString *)category complect:(void(^)(BOOL result))complectBlock
{
    dispatch_queue_t concurrentQueue = dispatch_queue_create("my.CreateNotifaction.queue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(concurrentQueue, ^{
        NSArray * array = [[UIApplication sharedApplication] scheduledLocalNotifications];
        for (UILocalNotification * notication in array) {
            if ([notication.category isEqualToString:@"MessageLocalNotifaction"]) {
                [[UIApplication sharedApplication] cancelLocalNotification:notication];
                notication.applicationIconBadgeNumber = 0;
                complectBlock(YES);
            }
        }
        
    });
}
@end
